import * as fs from 'node:fs'
import { IConfigs } from './interfaces'
import { CONFIGS_FILE } from './paths'
import { readJson, writeJson } from './utils'
import { ipcMain } from 'electron-better-ipc'

// 默认配置
export const getDefaultConfigs = (): IConfigs => {
    const configs: IConfigs = {
        server: {
            host: '127.0.0.1',
            port: 5180
        }
    }
    return configs
}

// 读取配置
export const readConfigs = () => {
    if (!fs.existsSync(CONFIGS_FILE)) {
        writeJson(CONFIGS_FILE, getDefaultConfigs())
    }
    return readJson(CONFIGS_FILE) as IConfigs
}

// 保存配置
export const saveConfigs = (data: IConfigs) => {
    writeJson(CONFIGS_FILE, data)
}

ipcMain.answerRenderer('readConfigs', () => {
    return readConfigs()
})
ipcMain.answerRenderer('saveConfigs', (data: IConfigs) => {
    saveConfigs(data)
})
